package com.faya.green.controller.main;

import com.faya.green.abnormal.ServiceException;
import com.faya.green.controller.BaseController;
import com.faya.green.enumeration.ResultEnum;
import com.faya.green.model.*;
import com.faya.green.model.web.OrganizationWeb;
import com.faya.green.service.BaseInfoService;
import com.faya.green.service.OrganizationService;
import com.faya.green.service.PostService;
import com.faya.green.service.UserService;
import com.faya.green.utils.CommonUtils;
import com.faya.green.utils.DateUtils;
import com.faya.green.utils.ImgUtils;
import com.google.gson.Gson;
import com.sun.tools.javah.LLNI;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 用户 ：LX
 * 创建时间： 2018/7/10. 23:42
 * 地点：广州
 * 目的: 主页控制层
 * 结果：
 */
@Controller
@RequestMapping("/main")
public class MainController extends BaseController {

    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private PostService postService;
    @Autowired
    private UserService userService;
    @Autowired
    private BaseInfoService baseInfoService;


    /**
     * 根据id 查询机构|部门信息(返回的数据，主键会自动转换为对应中文意思)
     * @param id 主键
     * @return
     */
    @RequestMapping(value = "getOrganization.php", method = RequestMethod.GET)
    @ResponseBody
    public ResultJson getOrganization(String id){
        ResultJson resultJson = new ResultJson();
        if (id == null){
            resultJson.setMsg("参数异常");
            resultJson.setStatus(ResultEnum.RESULT_ERROR.getStatus());
            return resultJson;
        }

        try {

            resultJson = organizationService.getOrganization(id);
            return resultJson;

        } catch (ServiceException e) {
            e.printStackTrace();
            resultJson.setMsg(e.getMsg());
            resultJson.setStatus(ResultEnum.RESULT_ERROR.getStatus());
        } catch (Exception e) {
            e.printStackTrace();
            resultJson.setMsg("查询机构失败！");
            resultJson.setStatus(ResultEnum.RESULT_ERROR.getStatus());
        }

        return resultJson;
    }

    /**
     * 递归 某节点下的全部子节点
     * @return
     */
    @RequestMapping(value = "getAllNode.php", method = RequestMethod.POST)
    @ResponseBody
    public String getAllNode(){
        //TODO 后续，判断权限，本部门的只能看到本部门的机构信息，只有有全部权限的，才能看到全部的机构

        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();

        //TODO 这里直接查询全部的机构， 这里的正常逻辑是用户进入后，得到所属岗位，然后查询到岗位隶属的部门，然后查询部门的信息，不在岗或者离开岗位的都无法被授权

        //超级管理员权限,直接遍历全部的机构
        List<OrganizationWeb> organizationWebs = organizationService.getAllNode();
        Gson gson = new Gson();
        return gson.toJson(organizationWebs);
    }

    /**
     * 新增或更新 机构|部门数据
     * @param organization 机构|部门信息
     * @param file 机构|部门 图标
     * @param operateType 操作类型 1 新增 2 更新
     * @param sonId 新增父节点的时候用这个保存原来的节点id
     * @return
     */
    @RequiresPermissions(value = {"user:sys.org:upd", "user:sys.org:add"}, logical = Logical.OR)
    @ResponseBody
    @RequestMapping(value = "/addOrUpdOraganization.php", method = RequestMethod.POST)
    public ResultJson addOrUpdOraganization(String sonId, String operateType, Organization organization, @RequestParam(value = "imgFile", required = false) MultipartFile file){
        ResultJson resultJson = new ResultJson();
        if (organization == null){
            resultJson.setMsg("请添加机构|部门数据");
            resultJson.setStatus(ResultEnum.RESULT_ERROR.getStatus());
            return resultJson;
        }
        if (CommonUtils.checkNull(operateType)){
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "无法识别操作类型", null);
        }

        try {

            resultJson = organizationService.addOrUpdOraganization(sonId, organization, file, operateType);
            return resultJson;

        } catch (ServiceException e) {
            e.printStackTrace();
            resultJson.setMsg(e.getMsg());
            resultJson.setStatus(ResultEnum.RESULT_ERROR.getStatus());
        } catch (Exception e) {
            e.printStackTrace();
            resultJson.setMsg("新增机构失败！");
            resultJson.setStatus(ResultEnum.RESULT_ERROR.getStatus());
        }

        return resultJson;
    }


    /**
     * 删除一个节点
     * @param id 节点ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delOrg.php", method = RequestMethod.GET)
    public ResultJson delOrg(String id){
        try {

            organizationService.delOrganization(id);
            return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "删除机构成功", null);

        } catch (ServiceException e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), e.getMsg(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "删除机构失败", null);
        }
    }

    /**
     * 获取所有的根节点，即根机构
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAllRootNode.php", method = RequestMethod.GET)
    public ResultJson getAllRootNode(){
        ResultJson resultJson = new ResultJson();
        try {
            List<Organization> rootNode = organizationService.getAllRootNode();
            resultJson.setMsg("查询成功");
            resultJson.setStatus(ResultEnum.RESULT_SUCCESS.getStatus());
            resultJson.setObject(rootNode);
            return resultJson;

        } catch (Exception e) {
            e.printStackTrace();
            resultJson.setMsg("查询失败");
            resultJson.setStatus(ResultEnum.RESULT_ERROR.getStatus());
            return resultJson;
        }
    }

    /**
     * 跳转到权限主界面
     * @return
     */
    @RequestMapping(value = "/main.php", method = RequestMethod.GET)
    @RequiresPermissions("user:main:*")
    public String main(ModelMap modelMap){
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        modelMap.put("user", user);

        //超级管理员权限,直接遍历全部的机构
        List<OrganizationWeb> organizationWebs = organizationService.getAllNode();
        Gson gson = new Gson();
        String json =  gson.toJson(organizationWebs);
        modelMap.put("jsonStr", json);

        return "/main/main";
    }

    /**
     * 跳转到主页
     * @return
     */
    @RequestMapping("/indexUrl.php")
    public String indexUrl(ModelMap modelMap){
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        modelMap.put("user", user);
        modelMap.put("choiceView", "index");

        return "/common/trunk";
    }


    /**
     * 跳转到核心主干页面
     * @param modelMap
     * @return
     */
    @RequestMapping("trunkUrl.php")
    @RequiresRoles("admin")
    public String trunkUrl(ModelMap modelMap){
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        modelMap.put("userTrunk", user);
        //index页面展示哪一个页面
        modelMap.put("choiceView", "baseInfo");

        return "/common/trunk";
    }

    /**
     * 获取部门图片
     * @param id 图片的id
     * @param response
     */
    @RequestMapping("/getOrgImgHred")
    public void getImgHred(String id, HttpServletResponse response){
        ImgUtils.readImg(id, response, "orgImg", null);
    }


    /**
     * 跳转到岗位操作页面
     * @param orgId 机构|部门的id
     * @param postId 岗位ID
     * @param postId operationType 操作类型, add 新增 upd 更新  query 查询
     * @return
     */
    @RequestMapping("/postAddOrUpdUrl.php")
    public String postAddOrUpdUrl(ModelMap modelMap,String operationType, String orgId, String postId){
        modelMap.put("orgId", orgId);
        modelMap.put("operationType", operationType);

        if ("query".equals(operationType) || "upd".equals(operationType)){
            Post post = postService.getPostById(postId);
            modelMap.put("postEdit", post);

            //数据转换
            if (!CommonUtils.checkNull(post.getType())){
                BaseInfo baseInfoByType = baseInfoService.getBaseInfoById(post.getType());
                if (baseInfoByType != null){
                    modelMap.put("type", baseInfoByType.getKey());
                }
            }
            if (!CommonUtils.checkNull(post.getPostLevel())){
                BaseInfo baseInfoByPostLevel = baseInfoService.getBaseInfoById(post.getPostLevel());
                if (baseInfoByPostLevel != null){
                    modelMap.put("postLevel", baseInfoByPostLevel.getKey());
                }
            }
            if (!CommonUtils.checkNull(post.getGrade())){
                BaseInfo baseInfoByGrade = baseInfoService.getBaseInfoById(post.getGrade());
                if (baseInfoByGrade != null){
                    modelMap.put("grade", baseInfoByGrade.getKey());
                }
            }
            if (!CommonUtils.checkNull(post.getRank())){
                BaseInfo baseInfoByRank = baseInfoService.getBaseInfoById(post.getRank());
                if (baseInfoByRank != null){
                    modelMap.put("rank", baseInfoByRank.getKey());
                }
            }

        }

        return "/main/mainPost";
    }


    /**
     * 根据岗位id删除岗位
     * @param postId 岗位id
     * @return
     */
    @GetMapping("/delPost.php")
    @ResponseBody
    @RequiresPermissions("user:sys.post:del")
    public ResultJson delPost(String postId){
        try {

            postService.delPost(postId);
            return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "岗位信息删除成功", null);


        } catch (ServiceException e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), e.getMsg(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "岗位信息删除失败", null);
        }
    }

    /**
     * 新增或更新岗位
     * @param post 岗位信息
     * @param orgId 隶属机构的id
     * @param operationType  操作类型, add 新增 upd 更新  query 查询
     * @return
     */
    @RequestMapping("/addOrUpdatePost.php")
    @ResponseBody
    @RequiresPermissions(value = {"user:sys.post:add", "user:sys.post:add"}, logical = Logical.OR)
    public ResultJson addOrUpdatePost(String operationType, Post post, String orgId){
        try {

            Post savaPost = postService.addOrUpdatePost(operationType, post, orgId);
            if ("add".equals(operationType)){
                return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "岗位信息添加成功", savaPost);
            } else if ("upd".equals(operationType)){
                return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "岗位信息更新成功", savaPost);
            } else {
                return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "操作成功", savaPost);
            }

        } catch (ServiceException e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), e.getMsg(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "新增岗位失败", null);
        }

    }

    /**
     * 找到指定机构|部门下的全部岗位
     * @param orgId 机构|岗位 ID
     * @return
     */
    @RequestMapping("/getPostOnOrg.php")
    @ResponseBody
    public ResultJson getPostOnOrg(String orgId){
        try {

            List<Post> postList = postService.getPostOnOrg(orgId);
            return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(), "岗位查找成功", postList);

        } catch (ServiceException e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), e.getMsg(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "岗位查找失败", null);
        }
    }


    /**
     * 找到指定机构|部门下的岗位,分页
     * @param orgId 机构|部门 ID
     * @param page 页码
     * @param limit 每页显示数量
     * @return
     */
    @GetMapping("/getPostOnOrgPage.php")
    @ResponseBody
    public ResultJson getPostOnOrgPage(String orgId, Integer page, Integer limit){
        try {

            return postService.getPostOnOrgPage(orgId, page, limit);

        } catch (ServiceException e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), e.getMsg(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "分页查询失败", null);
        }
    }

    /**
     * 找到指定岗位下的用户,分页
     * @param postId 岗位 ID
     * @param page 页码
     * @param limit 每页显示数量
     * @return
     */
    @GetMapping("/getUserOnPostPage.php")
    @ResponseBody
    public ResultJson getUserOnPostPage(String postId, Integer page, Integer limit){
        try {

            return userService.getUserOnPostPage(postId, page, limit);

        } catch (ServiceException e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), e.getMsg(), null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultJson(null, ResultEnum.RESULT_ERROR.getStatus(), "分页查询失败", null);
        }
    }


    /**
     * 跳转到用户新增页面
     * @param modelMap
     * @param id 相关联的岗位的id
     * @return
     */
    @RequestMapping("/addUsertUrl.php")
    public String addUsertUrl(ModelMap modelMap, String id){
        Post post = postService.getPostById(id);
        modelMap.put("post", post);
        //添加标识
        modelMap.put("viewType", "3");
        return "/main/mainUser";
    }
}
